var totalPeers = 0;
var maxLines = 0;
var maxPeerLine = 0;
var oldPeers = [];

function destroyPeer(idPeer) {
	el = document.getElementById('td'+idPeer);
	if (el){
	el.parentNode.removeChild(el);
	}
}

function killAllPeers(){
	tablePeers = document.getElementById('peers');
	while(tablePeers.rows.length>=1){
		tablePeers.deleteRow(tablePeers.rows.length-1);
	}
}

function createPeer(idPeer,cidPeer) {
	tablePeers = document.getElementById('peers');
	tableRows = tablePeers.rows.length;
	
	if(tableRows == 0 || tablePeers.rows[(tableRows-1)].cells.length == maxPeerLine && (tableRows-1) <= maxLines){
		tablePeers.insertRow(tableRows);
		tableRows = tablePeers.rows.length;
	}
	
	if ( tableRows <= maxLines){
		NewPeer = document.createElement('td');
		NewPeer.setAttribute('id', "td"+idPeer);
		divPronta = "<div id=\""+idPeer+"\" class=\"peer\">\n";
		divPronta = divPronta.concat("<img id=\"peerEImage"+idPeer+"\" class=\"peerEImage\" />\n");
		divPronta = divPronta.concat("<div class=\"peerNumber\">&nbsp;"+idPeer+"&nbsp;</div>\n");
		divPronta = divPronta.concat("<div class=\"peerCallerID\" id=\"CallerID"+idPeer+"\">&nbsp;"+cidPeer+"&nbsp;</div>\n");
		divPronta = divPronta.concat("<div class=\"peerExtension\" id=\"Extension"+idPeer+"\">&nbsp;</div>\n");
		divPronta = divPronta.concat("<div class=\"peerTime\" id=\"Time"+idPeer+"\">&nbsp;</div>\n");
		divPronta = divPronta.concat("</div>\n");
		NewPeer.innerHTML = divPronta;
		tablePeers.rows[(tableRows-1)].appendChild(NewPeer);
	}
}

function setPeerPos(e){
	Ppeer = getPosition(e);
	e.style.position = 'absolute';
	e.style.top = Ppeer.y+"px";
	e.style.left = Ppeer.x+"px";
}

function organize(Larg,Altu){
	topo = document.getElementById('Top');
	menu = document.getElementById('Menu');
	corpo = document.getElementById('MainBody');
	contPeers = document.getElementById('contPeers');
	base = document.getElementById('Base');
	
	// configurando o tamanho do menu
	menu.style.height = (Altu - (topo.offsetHeight+base.offsetHeight))+'px';
	
	// configurando o tamanho do corpo size
	corpo.style.height = (Altu - (topo.offsetHeight+base.offsetHeight))+'px';
	corpo.style.width = (Larg - menu.offsetWidth)+'px';
	
	// configurando o tamanho do contPeers
	contPeers.style.height = (corpo.offsetHeight-10)+'px';
	contPeers.style.width  = (corpo.offsetWidth-20)+'px';
	contPeers.style.margin = '5px 10px';
	
	// recarrega os ramais
	killAllPeers();
	maxPeerLine = Math.round(document.getElementById('contPeers').offsetWidth/138);
	maxLines = Math.round(document.getElementById('contPeers').offsetHeight/40);
	loadPeers(allPeers);
}

function loadPeers(Peers){
tablePeers = document.getElementById('peers');
this.Peers = Peers.sort();
if(Peers != oldPeers.sort() || tablePeers.rows.length == 0){
for(i=0;i<Peers.length;i++){
	createPeer(Peers[i][0],Peers[i][1]);
}
window.oldPeers = Peers;
}
}